package com.zx.dsptuneup_cloud.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.google.android.material.tabs.TabLayout;
import com.gyf.barlibrary.ImmersionBar;
import com.orhanobut.hawk.Hawk;
import com.zx.dsptuneup_cloud.Adapter.MultiFragmentPagerAdapter;
import com.zx.dsptuneup_cloud.App;
import com.zx.dsptuneup_cloud.Base.BaseActivity;
import com.zx.dsptuneup_cloud.Base.BaseFragment;
import com.zx.dsptuneup_cloud.Base.NoScrollViewPager;
import com.zx.dsptuneup_cloud.ProtocolTools.Init;
import com.zx.dsptuneup_cloud.R;
import com.zx.dsptuneup_cloud.Tools.ByteToString;
import com.zx.dsptuneup_cloud.Tools.Constant;
import com.zx.dsptuneup_cloud.Tools.NumberBaseConversionUtil;
import com.zx.dsptuneup_cloud.Tools.ProtocolServiceUtil;
import com.zx.dsptuneup_cloud.Util.CommonAction;
import com.zx.dsptuneup_cloud.Util.Constants;
import com.zx.dsptuneup_cloud.Util.InterceptionStringUtil;
import com.zx.dsptuneup_cloud.Util.Netty.NettyListener;
import com.zx.dsptuneup_cloud.Util.StringUtil;
import com.zx.dsptuneup_cloud.fragment.AudioMatrixFragment;
import com.zx.dsptuneup_cloud.fragment.InputFragment;
import com.zx.dsptuneup_cloud.fragment.OutPutFragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;

import static com.zx.dsptuneup_cloud.App.getContext;


public class HomeActivity extends BaseActivity implements NettyListener {
    @BindView(R.id.tab_title)
    TabLayout tabTitle;
    @BindView(R.id.main_viewpager)
    NoScrollViewPager viewPager;
    @BindView(R.id.iv_search)
    ImageView rightView;
    @BindView(R.id.ic_nav)
    ImageView ic_nav;
    @BindView(R.id.matrix_tv)
    TextView matrix_tv;
    @BindView(R.id.progressBar_ll)
    RelativeLayout progressBarLl;

    private Handler handler;
    private Runnable runnable1;
    private Runnable runnable2;
    private Runnable runnable3;
    private Runnable runnable4;
    private Runnable runnable5;
    private Runnable runnable9;
    /**
     * 点击返回时间
     */
    private long time = 2000;
    private long first_time = 0;
    //viewPager会缓存的Fragment数量
    private static final int VIEWPAGER_OFF_SCREEN_PAGE_LIMIT = 2;
    private final String TAG = "HomeActivity";

    private List<BaseFragment> fragments = new ArrayList<>();
    private MultiFragmentPagerAdapter mPagerAdapter;

    private BaseFragment input = new InputFragment();
    private BaseFragment output = new OutPutFragment();
    private BaseFragment matrix = new AudioMatrixFragment();
    private String ip;
    private  boolean isMatrix=false;
    private int delayedNum=58;
    private MyReceiver myReceiver;
    private int  fourteenNum=0;//14输入通道包数量标识
    private int eightNum=0;//8通道输出数量标识
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.updateNum);
        myReceiver = new MyReceiver();
        //注册广播
        registerReceiver(myReceiver,intentFilter);
        initUI();
        progressBarLl.setVisibility(View.VISIBLE);
        App.getContext().getNettyClient().setListener(HomeActivity.this);
        setQuery();  // 查询指令

 /*       // 初始化发送指令
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Init.initData1();
                }catch (Exception e){

                }
            }
        }).start();*/
        matrix_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(HomeActivity.this, MatrixActivity.class);
                startActivity(intent);

            }
        });
    }


    protected void initUI() {
        ImmersionBar.with(this)
//                .transparentBar()
                .statusBarColor(R.color.white)
                .statusBarDarkFont(true)
                .init();

        mPagerAdapter = new MultiFragmentPagerAdapter(getSupportFragmentManager());
        fragments.clear();
        fragments.add(input);
        fragments.add(output);
        fragments.add(matrix);
//        fragments.add(new BlueFragment());
        mPagerAdapter.init(fragments);


        viewPager.setOffscreenPageLimit(VIEWPAGER_OFF_SCREEN_PAGE_LIMIT);
        viewPager.setAdapter(mPagerAdapter);

        viewPager.setCurrentItem(0);
        mPagerAdapter.getItem(0).setUserVisibleHint(true);
        tabTitle.setupWithViewPager(viewPager);
        tabTitle.setTabTextColors(Color.parseColor("#868686"), Color.parseColor("#0A0A0A"));
//        tabTitle.setTabTextColors(R.color.title_normal,R.color.black);
        // 无效
        tabTitle.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.black));

        setSelectTextBoldAndBig(Objects.requireNonNull(tabTitle.getTabAt(0)));
        initTabListener();

        //  设置
        rightView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(HomeActivity.this, SettingActivity.class);
                startActivity(intent);
            }
        });

    }

    /**
     * 查询状态指令
     */
    private void setQuery() {
        handler = new Handler();
        runnable5 = new Runnable() {
            @Override
            public void run() {
                App.getContext().getProtocolServiceUtil().selectEquipmentNumbe();
                handler.postDelayed(this, delayedNum*1000);

            }
        };
        handler.postDelayed(runnable5, 800);
   /*       runnable2 = new Runnable() {
            @Override
            public void run() {
                App.getContext().getProtocolConversion().setQUERY();
//                handler.postDelayed(this, 20000);
            }
        };*/

        // 查询8通道数据
     /*   runnable3 = new Runnable() {
            @Override
            public void run() {
               // App.getContext().getProtocolServiceUtil().selectData8Channel();
               // handler.postDelayed(this, 60000);

            }
        };*/

    }

    private void initTabListener() {
        tabTitle.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setSelectTextBoldAndBig(tab);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                tab.setCustomView(null);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    @Override
    public void onMessageReaderTimeout() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

            }
        });
    }

    /**
     * 回调客户端接收的信息
     * I/System.out: 客户端开始读取服务端过来的信息
     * 2e637669 0632 0000 15a1 0400 00c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d0000000100000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d0000000100000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d0000000100000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d58020000a00f000000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d00000000e0008d00000000e0008d00000000e0008d00000000e0008d00000000e0008d000000010000204e1400000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d00000000e0008d00000000e0008d00000000e0008d00000000e0008d00000000e0008d000000010000204e1400000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d00000000e0008d00000000e0008d00000000e0008d00000000e0008d00000000e0008d000000010000204e1400000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d00000000e0008d00000000e0008d00000000e0008d00000000e0008d00000000e0008d000000010000204e1400000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d00000000e0008d00000000e0008d00000000e0008d00000000e0008d00000000e0008d000000010000204e1400000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d00000000e0008d00000000e0008d00000000e0008d00000000e0008d00000000e0008d000000010000204e1400000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d00000000e0008d00000000e0008d00000000e0008d00000000e0008d00000000e0008d000000010000204e1400000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d00000000e0008d00000000e0008d00000000e0008d00000000e0008d00000000e0008d000000010000204e1400000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d00000000e0008d00000000e0008d00000000e0008d00000000e0008d00000000e0008d000000010000204e1400000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d00000000e0008d00000000e0008d00000000e0008d00000000e0008d00000000e0008d000000010000204e1400000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d00000000e0008d00000000e0008d00000000e0008d00000000e0008d00000000e0008d000000010000204e1400000040008d0000000060008d0000000000008d0000000020008d00000000c0008d00000000e0008d0000000080008d00000000a0008d0000000040018d0000000060018d00000000e0008d00000000e0008d00000000e0008d00000000e0008d00000000e0008d000000010000204e140000000000002e646e0d
     */
    @Override
    public void onMessageResponse(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //  客户端开始读取服务端过来的信息
                //  StringUtil.dealWithMsgReceive(msg);
                if (msg.length() < 28) {
                    return;

                }
                String order1 = msg.substring(24, 28);//指令
                Log.d(TAG+"kkkk", order1 + "  长度" + msg.length() + "  数据=" + msg + "");
                switch (order1) {
                    case "4101":
                        InterceptionStringUtil.getData14Channel(msg);
                        fourteenNum++;
                        if (14==fourteenNum){
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    fourteenNum=0;
                                    App.getContext().getProtocolServiceUtil().selectData8Channel();
                                }
                            }, 980);//毫秒

                        }
                        break;
                    case "4103":
                        InterceptionStringUtil.getData8Channel(msg);
                        eightNum++;
                        if (8==eightNum){
                         //   Toast.makeText(HomeActivity.this,"8通道输出数据数据加载完成",Toast.LENGTH_LONG).show();
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    eightNum=0;
                                    progressBarLl.setVisibility(View.GONE);
                                    App.getContext().getProtocolServiceUtil().selectDataRemot();
                                }
                            }, 980);//毫秒


                        }

                        break;
                    case "4105":
                        if ((msg.length()==804)){
                            isMatrix=true;
                            Hawk.put("isMatrix",isMatrix);
                        }
                        if ("656e642e".equals(msg.substring(msg.length() - 8, msg.length()))) ;
                    {
                        Intent intent = new Intent(Constants.RESH_RECEIVER_BROADCAST);
                        sendBroadcast(intent);
                        Hawk.put("Matrix", msg);
                        Log.d("Matrixhfgf",msg);
                    }
                    // 查询14通道数据
                    App.getContext().getProtocolServiceUtil().selectData14Channel();
                    break;
                    case "4107":
                        break;
                    case "4109":
                        InterceptionStringUtil.setDataRemote(msg);
                        //查询心跳  获取设备型号、版本号
                        App.getContext().getProtocolServiceUtil().selectHeartBeat();
                        break;
                    case "410b":
                        InterceptionStringUtil.getDataInputParame(msg);
                      /*  //回复输入通道设置参数
                        Log.d(TAG,msg+"通道="+ByteToString.strTo10(msg.substring(32,34))+" 事件="+msg.substring(34,36)+
                                " 几段="+ByteToString.strTo10(msg.substring(36,38))+" type="+msg.substring(38,40)+"  频率="+ByteToString.strTo10(msg.substring(40,44))+
                                " q值="+ NumberBaseConversionUtil.SixToDecimalTen(msg.substring(44,48))+"  增益="+NumberBaseConversionUtil.SixToDecimalTen(msg.substring(48,52)));*/
                        break;
                    case "410d":
                        InterceptionStringUtil.getDataInputParame(msg);
                        break;
                    case "410f":
                        InterceptionStringUtil.getDataMatrix(msg);
                     //   Toast.makeText(HomeActivity.this,"矩阵数据数据加载完成",Toast.LENGTH_LONG).show();
                        break;
                    case "0002":
                        InterceptionStringUtil.getHeartBeat(msg);
                        break;

                    case "7706":
                        String num= msg.substring(32, 36);
                        Log.d("sadfsfas",num);
                        Hawk.put("group_number",num);//当前设备编组
                        Hawk.put("macAdress",msg.substring(36, 48));//当前设备mac地址  用于恢复出厂设置
                        //只执行一次矩阵数据查询
                        App.getContext().getProtocolServiceUtil().selectDataMatrix();

                        break;
                    case "4113":
                        InterceptionStringUtil.getDataRemote(msg);
                        break;

                }
//
            }
        });
    }

    //连接状态变化的时候 会走这
    @Override
    public void onServiceStatusConnectChanged(final int statusCode) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (statusCode == NettyListener.STATUS_CONNECT_SUCCESS) {
                    Log.e(TAG, "STATUS_CONNECT_SUCCESS:");
                    if (App.getContext().getNettyClient().getConnectStatus()) {
                    }
                } else {
                    Log.e(TAG, "onServiceStatusConnectChanged:" + statusCode);
                    // 连接断开
                    Toast.makeText(HomeActivity.this, "连接断开", Toast.LENGTH_LONG).show();
                    //  App.getContext().getNettyClient().disconnect();
                    // CommonAction.getInstance().OutSign();
                    App.getContext().getNettyClient().reconnect();
                    // startActivity(new Intent(HomeActivity.this, LoginActivity.class));
                }
            }
        });
    }


    private void setSelectTextBoldAndBig(TabLayout.Tab tab) {
        TextView textView = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.design_layout_tab_text, null);
        textView.setText(tab.getText());
        textView.setScaleY(1.1f);
        textView.setScaleX(1.1f);
//        textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        textView.setTextColor(Color.parseColor("#0A0A0A"));
        tab.setCustomView(textView);
    }

    @Override
    public void onBackPressed() {
        long cTime = new Date().getTime();
        if (first_time == 0 || cTime - first_time > time) {
            first_time = cTime;
            Toast.makeText(getApplicationContext(), "再按一次程序退出", Toast.LENGTH_SHORT).show();
        } else {
            //  断开连接
            App.getContext().getNettyClient().disconnect();
            //  取消心跳
         /*   handler.removeCallbacks(runnable1);
            handler.removeCallbacks(runnable2);
            handler.removeCallbacks(runnable4);*/
            handler.removeCallbacks(runnable5);
         //   handler.removeCallbacks(runnable9);
            super.onBackPressed();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("onPause", "onPause called");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myReceiver!=null){
            unregisterReceiver(myReceiver);

        }

        Log.e("onDestroy", "onDestroy called");
    }
    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            delayedNum=58;

        }
    }
}
